$(function () { // document ready

		var currentDate = moment(new Date()).format('YYYY-MM-DD');

		$('#calendar').fullCalendar({
			customButtons: {
				addEventButton: {
					text: '新增布岗',

					click: function () {
						$('#addModal').modal('toggle');   //打开模态框
					}
				},
				eventModel : {
					text: '模式切换'
				}
			},
			now: currentDate,
			editable: true,
			aspectRatio: 1.8,
			slotWidth:50,
			scrollTime: '00:00',
			duration: { hours: 0.5 },
			contentHeight: 454,
			header: {
				left: 'today prev,next', //addEventButton
				center: 'title',
				right: 'timelineDay'  //timelineDay eventModel
			},
			defaultView: 'timelineDay',
			schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',  //scheduler 商业项目许可证  (须开源)
			views: {
				timelineThreeDays: {
					type: 'timeline',
					duration: { days: 3 }
				}
			},
			resourceAreaWidth: '30%',
			resourceColumns: [
				{
					// group: true,
					labelText: '岗位',
					field: 'building'
				},
				{
					labelText: '班种',
					field: 'class'
				},
				{
					labelText: '班次',
					field: 'shift_id'
				}

			],
			eventOverlap: false, // will cause the event to take up entire resource height
			resources: [
				{ id: '505301', building: '值班站长', class: '大四班', shift_id: '日班' },
				{ id: '505302', building: '值班站长', class: '大四班', shift_id: '夜班' },
				{ id: '505303', building: '行车值班员', class: '大四班', shift_id: '日班' },
				{ id: '505304', building: '行车值班员', class: '大四班', shift_id: '夜班' },
				{ id: '505305', building: '设备值班员', class: '做一休一', shift_id: '日班' },
				{ id: '505306', building: '站厅巡视岗', class: '早中班', shift_id: '早班' },
				{ id: '505307', building: '站厅巡视岗', class: '早中班', shift_id: '中班' },
				{ id: '505308', building: '巡视岗站务员(机动)', class: '早中班', shift_id: '早班' },
				{ id: '505309', building: '巡视岗站务员(机动)', class: '早中班', shift_id: '中班' },
				{ id: '505310', building: '上行站台岗', class: '早中班', shift_id: '早班' },
				{ id: '505311', building: '上行站台岗', class: '早中班', shift_id: '中班' },
				{ id: '505312', building: '下行站台岗', class: '大四班', shift_id: '日班' },
				{ id: '505313', building: '下行站台岗', class: '大四班', shift_id: '晚班' },
				// { id: 'g', building: '上行站台岗', class: '早中班', children: [
				// 	{ id: 'g1', class: '早班' },
				// 	{ id: 'g2', class: '中班' }
				// ]},
			],
			events: function (start, end, timezone, callback) {
				$.ajax({
					url: 'http://127.0.0.1:10016/post/renderPostEvent',
					type: 'GET',
					data: {
						start: start._d.toISOString().substr(0, 10),
						// end: end._i
					},
					success: function (data) {

						if (data.code == 'success') {
							var events = [];
							if (data.data && data.data.length != 0) {
								data.data.forEach(function (element) {
									events.push({
										title: element.title,
										id: element.id,
										resourceId: element.resourceId,
										start: element.start,
										end: element.end,
										post: element.post,
										postValue: element.postValue,
										postId: element.postId,
										postIdValue: element.postIdValue,
										area: element.area,
										areaValue: element.areaValue,
										item: element.item
									})
								});
							}

							callback(events);

						} else {
							toastr[data.code](data.message);
						}


					}
				});
				
			},

			eventRender: function (event, element) {
				element.attr('role', 'button');
				element.attr('tabindex', 0);
				element.attr('data-toggle', 'popover')
				element.popover({
					container: 'body',  //操作弹出框附加在哪个元素上  选择body 不会导致在边界打开弹出框将元素挤变形
					trigger: 'manual',  //触发方式 manual
					placement: 'bottom', //top, bottom, left or right   弹出框弹出位置
					title: '操作',
					html: 'true',    //允许content 使用html
					content: "<div><button type='button' class='btn btn-default' onclick='editPostData()' data-toggle='modal' data-target='#addModal' data-whatever='@edit'>查看</button></div><div><button type='button' class='btn btn-default' onclick='eventDel()'>删除</button></div>",   //可以str 也可以 function()返回html str
				})
			},

			eventClick: function (calEvent, jsEvent, view) {

				var a = $('#calendar').fullCalendar('getEventResource', calEvent);
				console.log(calEvent);

				postData = renderPostData(calEvent);
				postData.start = calEvent.start._i;
				postData.end = calEvent.end._i;
				
				console.log(postData);
				if (!eventTemp) {
					// $(this).popover("show");
					var element = $(this);
					var txt = element.html();
				}
			},

			eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
				postData = renderPostData(event);

				postData.start = moment(event.start._i).add(delta._milliseconds,'milliseconds').format('YYYY-MM-DD HH:mm:ss');
				postData.end = moment(event.end._i).add(delta._milliseconds,'milliseconds').format('YYYY-MM-DD HH:mm:ss');

				var rescode = eventDataUpdate(postData);
				if(rescode){
					revertFunc();
				}
			},

			// 修改 fullcalendar.js reportEventResize()方法的返回对象 delta
			eventResize: function (event, delta,revertFunc, jsEvent, ui, view) {
				
				postData = renderPostData(event);
				
				if(delta.dateDelta._milliseconds){
					postData.start = moment(event.start._i).add(delta.dateDelta._milliseconds,'milliseconds').format('YYYY-MM-DD HH:mm:ss');
					postData.end = event.end._i;
				}else{
					postData.start = event.start._i;
					postData.end = moment(event.end._i).add(delta.durationDelta._milliseconds,'milliseconds').format('YYYY-MM-DD HH:mm:ss');
				}

				var rescode = eventDataUpdate(postData);
				if(rescode){
					revertFunc();
				}
				console.log(postData);
			},
		});

		$('.fc-eventModel-button').attr({'data-toggle':'dropdown','id':'eventModel','aria-haspopup':'true','aria-expanded':'true'});
		$('.fc-eventModel-button').addClass('dropdown-toggle');
		var modalDropDown = "<ul class='dropdown-menu eventModelMenu' aria-labelledby='eventModel'><li><a href='#'>模式1</a></li><li role='separator' class='divider'></li><li><a href='#'>模式2</a></li></ul>"
		

		$('.fc-right .fc-button-group').prepend('<div class="dropdown eventMOdelDropDown"></div>');
		$('.eventMOdelDropDown').append($('.fc-eventModel-button'));
		$(modalDropDown).insertAfter($('.fc-eventModel-button'));
		
		
	});

	var eventTemp;  //事件点击
	var eventData;

	var postData = {
		id: '',
		resourceId: '',
		start: '',    //开始时间
		end: '',      //结束时间
		post: '',     //岗位
		postValue: '',
		area: '',     //区域
		areaValue: '',
		postId: '',   //岗点
		postIdValue: ''
	}

	function alertJss(){
		toastr["warning"]("你有新消息了!");  
	}


	//event 弹出操作框点击事件监听
	$("body").on("click", function (event) {
		var target = $(event.target);

		if (!target.hasClass('fc-title')            //如果点击的不是 event 中的dom元素 就关闭操作弹出框
			&& !target.parent().hasClass('fc-event')
			&& !target.hasClass('fc-event')) {
			$('.fc-event').popover('hide');
			eventTemp = null;
		} else {
			var c = target[0].tagName.toLowerCase();  //拿到当前选中的event 去和上次点击的event对比 
			var event;
			if (c == 'span') {
				event = target.parent().parent();
			} else {
				event = target.parent();
			}
			if (eventTemp) {
				if (event.attr('aria-describedby') == eventTemp.attr('aria-describedby')) {
					$(eventTemp).popover('hide');    //和上次点击的相同 则关闭此event
					eventTemp = null;
				} else {
					$(eventTemp).popover('hide');   //不同也关闭此event 再打开当前点击的event
					$(event).popover('show');
					eventTemp = event;
				}
			} else {
				$(event).popover('show');             //不存在上次点击的event 则直接打开此event弹出操作框
				eventTemp = event;
			}
		}
	});

	//时间选择插件
	$('.form_datetime').datetimepicker({
		weekStart: 1,
		todayBtn: 1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		forceParse: 0,
		language: 'zh-CN',
		showMeridian: 1
	});

	//弹出框
	toastr.options = {  
		  closeButton: true,  
          debug: false,  
          progressBar: true,  
          positionClass: "toast-top-center",  
          onclick: null,  
          showDuration: "300",  
          hideDuration: "1000",  
          timeOut: "2000",  
          extendedTimeOut: "1000",  
          showEasing: "swing",  
          hideEasing: "linear",  
          showMethod: "fadeIn",  
          hideMethod: "fadeOut"  
     }; 

	//dropdown 组件下拉框选中传值
	//根据选中替换显示的文字 并获取其value
	$(".post-select a").on("click", function (event) {
		var target = $(event.target);
		postData.postValue = target.attr('value');
		postData.resourceId = target.attr('resourceId');
		postData.post = target.html();
		$('.postSelectBtnText').text(target.html());
	});

	$(".area-select a").on("click", function (event) {
		var target = $(event.target);
		postData.areaValue = target.attr('value');
		postData.area = target.html();
		$('.areaSelectBtnText').text(target.html());
	});

	$(".post-id-select a").on("click", function (event) {
		var target = $(event.target);
		postData.postIdValue = target.attr('value');
		postData.postId = target.html();
		$('.postIdSelectBtnText').text(target.html());
	});

	$(".workItem-select a").on("click", function (event) {
		var target = $(event.target);
		// postData.postIdValue = target.attr('value');
		postData.item = target.html();
		$('.workItemSelectBtnText').text(target.html());
	});

	$(".postBtn").on("click", function (event) {
		var target = $(event.target);
		var type = target.attr('id');
		if (type == 'post-submit') {
			Post_Event_Add()
		} else {
			Post_Event_Edit()
		}
	});

	function Post_Event_Add() {
		postData.start = $('#start_time').val();
		postData.end = $('#end_time').val();
		if (postData.end < postData.start) {
			toastr["warning"]("时间选择异常，结束时间早于开始时间！");  
			return;
		}
		postData.title = postData.start + '-' + postData.end + ' ' + postData.postId + ' 区域：' + postData.area + ' 工作：' + postData.item;
		console.log(postData);
		$.ajax({
			url: '/post/addPostEvent',
			data: postData,
			type: 'POST',
			dataType: 'json',
			success: function (data) {
				if (data.code == 'success') {
					// planScheduInfos = data.data;
					$('#calendar').fullCalendar('refetchEvents'); //重新获取event数据
					toastr[data.code](data.message);
					$('#addModal').modal('hide');
				} else {
					toastr[data.code](data.message);
					return data.code;
				}
			},
			error: function(){
				return 'error';
			}
		});

		var source = [postData];
	}

	function Post_Event_Edit() {
		postData.start = $('#start_time').val();
		postData.end = $('#end_time').val();
		if (postData.end < postData.start) {
			toastr['warning']("时间选择异常，结束时间早于开始时间！");
			return;
		}
		
		console.log(postData);
		eventDataUpdate(postData);
		var source = [postData];
		// $('#calendar').fullCalendar('addEventSource', source);
	}

	//清空表单数据
	$('.modal').on('hidden.bs.modal', function () {
		$('#start_time').val('');
		$('#end_time').val('');
		$('.postIdSelectBtnText').text("点击选择");
		$('.areaSelectBtnText').text("点击选择");
		$('.postSelectBtnText').text("点击选择");
		$('.workItemSelectBtnText').text("点击选择");
		postData = {};
	});


	$('.modal').on('show.bs.modal', function (event) {
		var recipient = $(event.relatedTarget).data('whatever');
		var modal = $(this)
		if (recipient) {
			modal.find('.modal-title').text('查看布岗');
			$('#start_time').val(postData.start);
			$('#end_time').val(postData.end);
			$('.postIdSelectBtnText').text(postData.postId);
			$('.areaSelectBtnText').text(postData.area);
			$('.postSelectBtnText').text(postData.post);
			$('.workItemSelectBtnText').text(postData.item);

			$('.postBtn').attr('id', 'post-edit');
		} else {
			modal.find('.modal-title').text('新增布岗');
			$('.postBtn').attr('id', 'post-submit');
		}

	})



	function editPostData() {
		
		// $('.modal').modal('show')
	}

	function eventDel() {
		$.ajax({
			url: '/post/delPostEvent',
			data: {
				pid: postData.id
			},
			type: 'POST',
			dataType: 'json',
			success: function (data) {
				if (data.code == 'success') {
					// planScheduInfos = data.data;
					$('#calendar').fullCalendar('refetchEvents'); //重新获取event数据
					toastr[data.code](data.message);
				} else {
					toastr[data.code](data.message);
				}
			}
		});
	}

	function renderPostData(event){
		postData = {
			id: event.id,
			resourceId: event.resourceId,
			// start: calEvent.start._i,    //开始时间
			// end: calEvent.end._i,      //结束时间
			post: event.post,     //岗位
			postValue: event.postValue,
			area: event.area,     //区域
			areaValue: event.areaValue,
			postId: event.postId,   //岗点
			postIdValue: event.postIdValue,
			item: event.item
		}
		return postData;
	}

	function eventDataUpdate(postData){
		postData.title = postData.start + '-' + postData.end + ' ' + postData.postId + ' 区域：' + postData.area + ' 工作：' + postData.item;
		$.ajax({
			url: '/post/updatePostEvent',
			data: postData,
			type: 'POST',
			dataType: 'json',
			success: function (data) {
				if (data.code == 'success') {
					// planScheduInfos = data.data;
					$('#calendar').fullCalendar('refetchEvents'); //重新获取event数据
					toastr[data.code](data.message);
					$('#addModal').modal('hide');
				} else {
					toastr[data.code](data.message);
					return data.code;
				}
			},
			error: function(){
				return 'error';
			}
		});
	}